package My

import (
	"fmt"
	"db2s/ETL"
	"db2s/global"
	"strings"
)

func (my TableInfoMeta) CustomizeTypeName(s global.TablesMetaInfoInput) (result global.ObjectNameReturnResult, err error) {
	var f1 any
	var event = "[MySQLCustomizeTypeName]"
	result.BaseResult.Sql = fmt.Sprintf("select ROUTINE_NAME from INFORMATION_SCHEMA.ROUTINES where  ROUTINE_TYPE = 'TYPE' AND ROUTINE_SCHEMA ='%v' %v",
		s.TableInfo.Schema, func() string {
			switch {
			case s.TableInfo.Table == "*":
				return ""
			case strings.Contains(s.TableInfo.Table, "%"):
				return fmt.Sprintf(" and ROUTINE_NAME like '%%%v%%'", s.TableInfo.Table)
			default:
				return fmt.Sprintf(" and ROUTINE_NAME = '%v'", s.TableInfo.Table)
			}
		}())
	if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
		Ss:           s,
		Event:        event,
		SelectSqlStr: result.BaseResult.Sql,
		Expect:       ETL.StringGarth,
	}); err != nil {
		return
	}
	result.Result = f1.([]string)
	return
}
func (my TableInfoMeta) CustomizeTypeExist(s global.TablesMetaInfoInput) (result global.ObjectExistReturnResult, err error) {
	var f1 any
	var event = "[MySQLCustomizeTypeExist]"
	result.BaseResult.Sql = fmt.Sprintf("select count(1) as `sum` from INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE = 'TYPE' and ROUTINE_SCHEMA = '%v' and ROUTINE_NAME = '%v'", s.TableInfo.Schema, s.TableInfo.Table)
	if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
		Ss:           s,
		Event:        event,
		SelectSqlStr: result.BaseResult.Sql,
		Expect:       ETL.Map,
	}); err != nil {
		return
	}
	if fmt.Sprintf("%v", f1.(map[string]any)["sum"]) == "1" {
		result.Result = true
	}
	return
}

func typePrintInfo(x global.TypeResultDefinition) (res string) {
	/*
		CREATE OR REPLACE TYPE "PCMS"."F_GCJ" as object (gcj_lat number, gcj_lon number);
		CREATE OR REPLACE TYPE "PCMS"."SEQ_ARRAY" is table of number;
		CREATE OR REPLACE TYPE "PCMS"."OPTICABSEG_OBJ" as object (
		  id                NUMBER(10),
		  name              NVARCHAR2(500),
		  city_id           NUMBER(10),
		  county_id         NUMBER(10),
		  typecode          NUMBER(10),
		  status            NUMBER(10),
		  pro_task_id       NUMBER(10),
		  is_complete_lay   NUMBER(10),
		  related_system    NUMBER(10),
		  a_id              NUMBER(10),
		  a_type            NUMBER(10),
		  z_id              NUMBER(10),
		  z_type            NUMBER(10),
		  system_level      NUMBER(10),
		  wkt               NVARCHAR2(500),
		  shape             clob
		);
	*/
	res = fmt.Sprintf("CREATE OR REPLACE %v"+
		"/",
		x.Body,
	)
	return
}
func typeDefinitionConvert(x global.TypeResultDefinition) (convert global.TypeDefinitionConvertS) {
	return global.TypeDefinitionConvertS{
		Schema:    x.Schema,
		Name:      x.Name,
		Body:      x.Body,
		Comment:   x.Comment,
		Type:      x.Type,
		PrintInfo: x.PrintInfo,
	}
}
func (my SchemaObjectMeta) Type(s global.SchemaObjectInput) (result global.SchemaObjectReturnResult, err error) {
	var (
		f1    any
		x     global.TypeResultDefinition
		event = "[MySQLType]"
	)
	for _, v := range []string{
		fmt.Sprintf("SELECT\n"+
			"\tROUTINE_SCHEMA AS `schema`,\n"+
			"\tROUTINE_NAME AS `name`,\n"+
			"\tDEFINER  AS `permissions`,\n  "+
			"\tROUTINE_DEFINITION AS `body`,\n"+
			"\tROUTINE_COMMENT AS `comment`\n"+
			"FROM\n"+
			"\tinformation_schema.ROUTINES \n"+
			"WHERE 1 = 1\n"+
			"\tAND ROUTINE_TYPE = 'TYPE' \n"+
			"\tAND ROUTINE_SCHEMA = '%v' \n"+
			"\tAND ROUTINE_NAME = '%v'", s.Schema, s.Table),
	} {
		result.BaseResult.Sql = v
		if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
			Ss:           s,
			Event:        event,
			SelectSqlStr: result.BaseResult.Sql,
			Expect:       ETL.Map,
		}); err != nil {
			return
		}
		if err = global.MapSubToStructSubJsonName(mapNullActive(f1.(map[string]any)), &x); err != nil {
			return
		}
		x.Type = "type"
	}
	x.PrintInfo = typePrintInfo(x)
	result.TypeResult.Definition = x
	result.TypeResult.Convert = typeDefinitionConvert(x)
	return
}
func typePrintInfoConvert(s string) (res string) {
	res = strings.TrimSpace(s)
	if strings.HasSuffix(res, "/") {
		res = strings.TrimSpace(res[:len(res)-1])
	}
	if strings.HasSuffix(res, ";") {
		res = strings.TrimSpace(res[:len(res)-1])
	}
	return
}
func createType(s global.SchemaObjectInput) (result global.ObjectFixSqlS, err error) {
	result.CreateSql = append(result.CreateSql, fmt.Sprintf("use %v; \n"+
		"%v ;",
		s.Schema,
		typePrintInfoConvert(s.ObjectDefinition.TypeResult.Convert.PrintInfo)))
	return
}
